﻿/*
 * Copyright (C) 2012, Jesus Requejo <jesus.requejo@gmail.com> 
 * Licensed under Microsoft Public License (Ms-PL)
 * http://www.microsoft.com/en-us/openness/licenses.aspx#MPL
*/

namespace Infrastructure {
   using System;
   using System.Collections.Generic;
   using System.Linq;
   using System.Text;

   public static class PermissionsChecker {
      public static bool StartupApplicationsAuthorized(string userName) {

         PermissionsConfiguration permissions = ReadPermissions();
         bool isAuthorized = false;
         switch (permissions.StartupPermissions) {
            case StartupPermissions.Everybody:
               isAuthorized = true;
               break;
            case StartupPermissions.Admins:
               isAuthorized = Infrastructure.WindowsUsersUtils.UserIsInAdminGroup(userName);
               break;
            case StartupPermissions.Authorized:
               isAuthorized = permissions.AuthorizedStartupUsers.Select(u => u.Name).Contains(userName);
               break;
            default:
               break;
         }
         return isAuthorized;
      }

      public static bool LaunchManagerAuthorized(string userName) {
         Infrastructure.PermissionsFileSystemStorage storage = new PermissionsFileSystemStorage();
         PermissionsConfiguration permissions = storage.ReadPermissionsConfiguration();
         bool isAuthorized = false;
         switch (permissions.ServiceManagerPermissions) {
            case ServiceManagerPermissions.Nobody:
               isAuthorized = false;
               break;
            case ServiceManagerPermissions.Admins:
               isAuthorized = Infrastructure.WindowsUsersUtils.UserIsInAdminGroup(userName);
               break;
            case ServiceManagerPermissions.Authorized:
               isAuthorized = permissions.AuthorizedStartupUsers.Select(u => u.Name).Contains(userName);
               break;
            default:
               break;
         }
         return isAuthorized;
      }

      public static PermissionsConfiguration CreateDefaultPermissions() {
         return new PermissionsConfiguration() {
            StartupPermissions = Infrastructure.StartupPermissions.Everybody,
            ServiceManagerPermissions = ServiceManagerPermissions.Nobody,
            AuthorizedStartupUsers = new List<WindowsUser>() { },
            AuthorizedServiceManagerUsers = new List<WindowsUser>() { }
         };
      }

      private static PermissionsConfiguration ReadPermissions() {
         try {
            Infrastructure.PermissionsFileSystemStorage storage = new PermissionsFileSystemStorage();
            var permissions = storage.ReadPermissionsConfiguration();
            return permissions;
         }
         catch (Exception) {
            var permissions = CreateDefaultPermissions();
            return permissions;
         }
      }      
   }
}
